<?php

namespace App\Http\Controllers\Attendance;

use App\Http\Controllers\Controller;
use App\Imports\Attendance\AttendanceImport;
use App\Models\Attendance\Attendance;
use App\Models\Attendance\AttendanceCollect;
use App\Models\Attendance\AttendanceData;
use App\Models\Personnel\PersonnelCleaner;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use App\Models\Dict;

class AttendanceController extends Controller
{
    /**
     * 获取打卡列表数据
     *
     * @param Request $request
     * @return void
     */
    public function attendanceList(Request $request)
    {
        $params = $request->all();

        if (isset($params['date'])) {
            $params['date'] = date('Y-m-d', strtotime($params['date']));
        } else {
            //如果没有查询日期,就查询打卡记录最后日期记录
            $sign_date = AttendanceCollect::query()
                ->groupBy('sign_date')
                ->orderByDesc('sign_date')
                ->first()
                ->sign_date;
            $params['date'] = date('Y-m-d', strtotime($sign_date));
        }
        $query = $this->getQuery($params);
        $data = $query->orderBy('line')->orderBy('license_plate_num')->get()->toArray();
        $result = [
            'lists' => $data,
            'driver' => isset($params['driver']) ? $params['driver'] : '',
            'license_plate_num' => isset($params['license_plate_num']) ? $params['license_plate_num'] : '',
            'date' => $params['date'],
            'line' => isset($params['line']) ? $params['line'] : '-1',
        ];
        return response()->formatJson($result);
    }
    /**
     * 根据查询条件拼接sql语句
     *
     * @param [array] $params
     * @return Builder
     */
    public function getQuery($params): Builder
    {
        $query = AttendanceCollect::query()
            ->where('sign_date', $params['date']);
        if (isset($params['license_plate_num'])) {
            $query->where('license_plate_num', 'like', '%' . $params['license_plate_num'] . '%');
        }
        if (isset($params['driver'])) {
            $query->where('driver', 'like', '%' . $params['driver'] . '%');
        }
        if (isset($params['line']) && -1 != $params['line']) {
            $query->where('line', $params['line']);
        }
        return $query;
    }

}
